package com.hahaliu.hahaliu.controller.user;

import com.hahaliu.hahaliu.common.result.Result;
import com.hahaliu.hahaliu.common.utils.JwtUtil;
import com.hahaliu.hahaliu.common.context.CurrentUser;
import com.hahaliu.hahaliu.pojo.dto.UserDTO;
import com.hahaliu.hahaliu.pojo.dto.UserLoginDTO;
import com.hahaliu.hahaliu.pojo.dto.UserRegisterDTO;
import com.hahaliu.hahaliu.pojo.entity.User;
import com.hahaliu.hahaliu.pojo.vo.UserLoginVO;
import com.hahaliu.hahaliu.service.user.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/user/user")
@Api(tags = "用户端用户相关接口")
@Slf4j
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private JwtUtil jwtUtil;
	@Autowired
	private CurrentUser currentUser;


	@PostMapping("/login")
	@ApiOperation("用户登录")
	public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
		log.info("用户登录：{}", userLoginDTO);

		User user = userService.login(userLoginDTO);

		String token = jwtUtil.createToken(user.getUId().toString(), "user");

		UserLoginVO userLoginVO = UserLoginVO.builder()
				.user(user)
				.token(token)
				.build();

		return Result.success(userLoginVO);
    }

	@PostMapping("/register")
	@ApiOperation(value = "用户注册")
	public Result register(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册：{}", userRegisterDTO);

        userService.register(userRegisterDTO);

        return Result.success();
    }

	@GetMapping("/personal/info")
	@ApiOperation(value = "查询当前用户信息")
	public Result<UserDTO> getPersonal() {
		UserDTO user = userService.getPersonalInfo();
		return Result.success(user);
	}

	@GetMapping("/{uId}")
    @ApiOperation(value = "查询用户信息")
    public Result<User> getById(@PathVariable Integer uId) {

		User user = userService.getById(uId);

        return Result.success(user);
    }

	@PostMapping("/update/info")
    @ApiOperation(value = "用户信息更新")
    public Result update(@RequestBody UserDTO userDTO) {
        log.info("用户更新：{}", userDTO);

		userService.updateUserInfo(userDTO);

        return Result.success();
    }

	/**
	 * 更新用户头像
	 * @param file  头像文件
	 * @return  成功则返回新头像url
	 */
	@PostMapping("/update/avatar")
	@ApiOperation(value = "更新用户头像")
	public Result<String> updateUserAvatar(@RequestParam("file") MultipartFile file) throws IOException {
		Integer uId = currentUser.getUserId();

		String url = userService.updateUserAvatar(uId, file);

        return Result.success(url);
	}

}
